package v1

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"teacher-helper/global"
	"teacher-helper/models"
	"teacher-helper/models/request"
	"teacher-helper/service"
)

func GetStudentList(c *gin.Context) {
	var queryInfo request.QueryInfo
	if err := c.ShouldBind(&queryInfo); err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
		return
	}
	claims, _ := c.Get("claims")
	user := claims.(*request.CustomClaims)
	if len(user.ClassIds) == 0 {
		c.JSON(202, gin.H{"msg": "当前用户目前还没有分配学生", "data": nil})
		return
	}
	Students, total, err := service.GetStudentList(queryInfo, user)
	if err != nil {
		c.JSON(203, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取学生列表成功", "data": map[string]interface{}{
			"students": Students,
			"total": total,
		}})
	}
	return
}

func GetOneStudentInfo(c *gin.Context)  {
	id, ok := c.GetQuery("id")
	stu_id, err := strconv.Atoi(id)
	if !ok || err != nil{
		c.JSON(201, gin.H{"msg": "参数有误", "data": nil})
		return
	}

	student, err := service.GetStudentByID(stu_id)
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取学生列表成功", "data": student})
	}
	return
}

func GetStuIDList(c *gin.Context) {
	Stu_ids, err := service.GetStuIDList()
	if err != nil {
		c.JSON(202, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "获取学生列表成功", "data": Stu_ids})
	}
	return
}

func AddOneStudent(c *gin.Context)  {
	var Student models.SysStudent
	if err := c.ShouldBindJSON(&Student);err != nil{
		global.Logger.Error(err.Error())
		c.JSON(201, gin.H{"msg": err})
		return
	}
	err := service.AddOneStudent(Student)
	if err != nil {
		c.JSON(202, gin.H{"msg": err})
	}else {
		c.JSON(http.StatusOK, gin.H{"msg": "添加学生成功"})
	}
	return
}

func UpdateStudent(c *gin.Context) {
	var Student models.SysStudent
	if err := c.ShouldBindJSON(&Student); err != nil {
		global.Logger.Error(err.Error())
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err := service.UpdateStudent(Student)
	if err != nil {
		global.Logger.Error(err.Error())
		c.JSON(202, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "修改学生成功", "data": nil})
	}
	return
}

func DeleteStudent(c *gin.Context) {
	id, ok := c.GetQuery("id")
	Id, err := strconv.Atoi(id)
	if !ok || err != nil {
		c.JSON(201, gin.H{"msg": "参数获取失败"})
		return
	}
	err = service.DeleteStudent(Id)
	if err != nil {
		c.JSON(201, gin.H{"msg": err, "data": nil})
	} else {
		c.JSON(http.StatusOK, gin.H{"msg": "删除学生成功", "data": nil})
	}
	return
}
